package com.ckf.city.controller;

import com.ckf.city.entity.City;
import com.ckf.city.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: serene
 * @date: 2020/9/19 16:35
 */
@RestController
public class CityController {

    @Autowired
    private CityService cityService;

    /**
     * 全查询
     * @return
     */
    @GetMapping("/test")
    public List<City> test(){
        return cityService.list();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/listId")
    public City listId(Integer id){
        return cityService.selectCityListId(id);
    }

    /**
     * 查询地址列表
     * @return
     */
    @GetMapping("/list")
    public Map list(){
        Map<String, Object> outMap = new HashMap<String, Object>();

        List<City> list = cityService.list();
        if (list!=null){
            outMap.put("result", list);
            outMap.put("success","成功");
        }else {
            outMap.put("fail","失败");
        }
        return outMap;
    }


    @GetMapping("getTree")
    public Map<String, Object> getTree(int id) {
        Map<String, Object> map = new HashMap<>();
        try {
            //查询出一个省
            City  province= cityService.selectCityListId(id);
            if (province != null) {
                //查询省下面的所有市
                List<City> citys = (List<City>) cityService.selectCityListId(province.getId());
                digui(citys);
                //调用递归算法查询市以下的区县
                province.setChildren(citys);
            }
            map.put("data", province);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public void digui(List<City> citys) {
        List<City> retList = new ArrayList<>();
        for (City c : citys) {
            retList = (List<City>) cityService.selectCityListId(c.getId());
            if (retList.size() > 0) {
                c.setChildren(retList);
                digui(retList); //循环调用自己
            }
        }
    }



}
